import { createGlobalStore } from "hox";
import { useEffect, useState } from "react";

export type LoginType = "admin" | "tourists" | null;

export const [useUserStore, getUserStore] = createGlobalStore(() => {
  const [loginType, setLogin] = useState<LoginType>(null);
  const [user, sUser] = useState<Record<string, any> | null>(null);

  const setUser = (
    loginType: "admin" | "tourists",
    user?: Record<string, any>
  ) => {
    sessionStorage.setItem("loginType", loginType);
    setLogin(loginType);
    user && sUser(user);
    user && sessionStorage.setItem("user", JSON.stringify(user));
  };

  useEffect(() => {
    const user = sessionStorage.getItem("user");
    user && sUser(JSON.parse(user));
    const loginType = sessionStorage.getItem("loginType");
    loginType && setLogin(loginType as any);
  }, []);

  const clearLogin = () => {
    setLogin(null);
    sUser(null);
    sessionStorage.removeItem("user");
    sessionStorage.removeItem("loginType");

    console.log("sessionStorage.getItem", sessionStorage.getItem("user"));
  };

  return {
    loginType,
    user,
    setUser,
    clearLogin,
  };
});
